package org.bemo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class HttpUtil {
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = null;
			if (param != null) {
				urlNameString = url + "?" + param;
			} else {
				urlNameString = url;
			}
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Remote Address", "111.161.99.246:443");

			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// ========
			connection.setRequestProperty("Host", "vip.api.47ks.com");
			connection.setRequestProperty("Cookie",
					"UM_distinctid=15b237687672b-0ba6006af0e16f-12616a4a-110400-15b2376876831d; CNZZDATA1260594368=116182521-1490945396-https%253A%252F%252Fv.qq.com%252F%7C1491543799; Hm_lvt_2d94b714156feffcd62dce77cabbc4e3=1491544749; Hm_lpvt_2d94b714156feffcd62dce77cabbc4e3=1491544749");
			connection.setRequestProperty("referer", "https://vip.api.47ks.com/");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
			conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			conn.setRequestProperty("X-AjaxPro-Method", "GetDataSource");
			conn.setRequestProperty("Content-Length", "443");
			conn.setRequestProperty("Referrer Policy", "no-referrer-when-downgrade");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			conn.setRequestProperty("user-agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");
			// ========
			conn.setRequestProperty("Host", "vip.api.47ks.com");
			conn.setRequestProperty("Cache-Control", "max-age=0");
			conn.setRequestProperty("Cookie",
					"UM_distinctid=15b237687672b-0ba6006af0e16f-12616a4a-110400-15b2376876831d; CNZZDATA1261559475=1559909885-1491032708-null%7C1491660487; yunsuo_session_verify=fab38e596b78b64c8a4e4ac09110fe2f; Hm_lvt_2d94b714156feffcd62dce77cabbc4e3=1491544749");
			conn.setRequestProperty("Referer",
					"https://vip.api.47ks.com/cp0309/?v=https://v.qq.com/x/cover/ttqxo9s3cblgofl.html");
			// ===============================================
			// conn.setRequestProperty("origin", "https://api.47ks.com");
			// conn.setRequestProperty(":scheme", "https");
			// conn.setRequestProperty(":authority", "api.47ks.com");
			// conn.setRequestProperty(":method", "POST");
			// conn.setRequestProperty(":path", "/config/webmain.php");

			/**
			 * Host: api.47ks.com User-Agent: Mozilla/5.0 (Windows NT 10.0;
			 * WOW64; rv:51.0) Gecko/20100101 Firefox/51.0 Accept:
			 * application/json, text/javascript, *0/*; q=0.01 Accept-Language:
			 * zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3 Accept-Encoding: gzip,
			 * deflate, br Content-Type: application/x-www-form-urlencoded;
			 * charset=UTF-8 X-Requested-With: XMLHttpRequest Referer:
			 * https://api.47ks.com/webcloud/?v=https://v.qq.com/x/cover/
			 * eo55ln1vqzma27t.html Content-Length: 327 Cookie:
			 * UM_distinctid=15b237687672b-0ba6006af0e16f-12616a4a-110400-
			 * 15b2376876831d;
			 * CNZZDATA1260594368=116182521-1490945396-https%253A%252F%252Fv.qq.
			 * com%252F%7C1491543799;
			 * Hm_lvt_2d94b714156feffcd62dce77cabbc4e3=1491544749;
			 * Hm_lpvt_2d94b714156feffcd62dce77cabbc4e3=1491544749 Connection:
			 * keep-alive Pragma: no-cache Cache-Control: no-cache
			 */
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				System.out.println(line);
				// switch (line.lastIndexOf(0)) {
				// case 0xefbb:
				// System.out.println("UTF-8");
				// break;
				// case 0xfffe:
				// System.out.println("Unicode");
				// break;
				// case 0xfeff:
				// System.out.println("UTF-16BE");
				// break;
				// default:
				// System.out.println("GBK");
				// }
				result += line;
			}

			// // 声明长度为5的byte数组
			// byte[] b = new byte[5];
			//
			//
			// // 声明len变量,用于存储read()方法读取的字节个数,还有其它作用
			// int len;
			//
			// InputStream is = conn.getInputStream();
			// // 使用while循环读取文本文件
			// while ((len = is.read(b)) != -1){
			// //
			// for循环用于循环读取数组中的元素,因为有可以是5有可能最后read()方法读入到byte数组中的不到5个元素,所以用len作为一个判断条件
			// // String s = new String(new byte[] { b[len - 2], b[len - 1] });
			// String s = new String(b, 0, len);
			// System.out.println(s);
			// System.out.println(len);
			// System.out.print((char) len);
			//
			// }

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

}
